home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2005 October / PCWOCT05.iso / Software / FromTheMag / XAMPP 1.4.14 / xampp-win32-1.4.14-installer.exe / xampp / php / pear / adodb / drivers / adodb-postgres64.inc.php < prev    next >
Encoding:
PHP Script  |  2005-05-17  |  30.7 KB  |  1,013 lines

  1. <?php
  2. /*
  3.  V4.63 17 May 2005  (c) 2000-2005 John Lim (jlim@natsoft.com.my). All rights reserved.
  4.   Released under both BSD license and Lesser GPL library license. 
  5.   Whenever there is any discrepancy between the two licenses, 
  6.   the BSD license will take precedence.
  7.   Set tabs to 8.
  8.   
  9.   Original version derived from Alberto Cerezal (acerezalp@dbnet.es) - DBNet Informatica & Comunicaciones. 
  10.   08 Nov 2000 jlim - Minor corrections, removing mysql stuff
  11.   09 Nov 2000 jlim - added insertid support suggested by "Christopher Kings-Lynne" <chriskl@familyhealth.com.au>
  12.                     jlim - changed concat operator to || and data types to MetaType to match documented pgsql types 
  13.              see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm  
  14.   22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <raser@mail.zen.com.tw>
  15.   27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <leen@wirehub.nl>
  16.   15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk. 
  17.   31 Jan 2002 jlim - finally installed postgresql. testing
  18.   01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type
  19.   
  20.   See http://www.varlena.com/varlena/GeneralBits/47.php
  21.   
  22.     -- What indexes are on my table?
  23.     select * from pg_indexes where tablename = 'tablename';
  24.     
  25.     -- What triggers are on my table?
  26.     select c.relname as "Table", t.tgname as "Trigger Name", 
  27.        t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",
  28.        t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",
  29.        p.proname as "Function Name"
  30.     from pg_trigger t, pg_class c, pg_class cc, pg_proc p
  31.     where t.tgfoid = p.oid and t.tgrelid = c.oid
  32.        and t.tgconstrrelid = cc.oid
  33.        and c.relname = 'tablename';
  34.     
  35.     -- What constraints are on my table?
  36.     select r.relname as "Table", c.conname as "Constraint Name",
  37.        contype as "Constraint Type", conkey as "Key Columns",
  38.        confkey as "Foreign Columns", consrc as "Source"
  39.     from pg_class r, pg_constraint c
  40.     where r.oid = c.conrelid
  41.        and relname = 'tablename';
  42.  
  43. */
  44.  
  45. // security - hide paths
  46. if (!defined('ADODB_DIR')) die();
  47.  
  48. function adodb_addslashes($s)
  49. {
  50.     $len = strlen($s);
  51.     if ($len == 0) return "''";
  52.     if (strncmp($s,"'",1) === 0 && substr(s,$len-1) == "'") return $s; // already quoted
  53.     
  54.     return "'".addslashes($s)."'";
  55. }
  56.  
  57. class ADODB_postgres64 extends ADOConnection{
  58.     var $databaseType = 'postgres64';
  59.     var $dataProvider = 'postgres';
  60.     var $hasInsertID = true;
  61.     var $_resultid = false;
  62.       var $concat_operator='||';
  63.     var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
  64.     var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
  65.     and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
  66.      'sql_packages', 'sql_sizing', 'sql_sizing_profiles') 
  67.     union 
  68.         select viewname,'V' from pg_views where viewname not like 'pg\_%'";
  69.     //"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
  70.     var $isoDates = true; // accepts dates in ISO format
  71.     var $sysDate = "CURRENT_DATE";
  72.     var $sysTimeStamp = "CURRENT_TIMESTAMP";
  73.     var $blobEncodeType = 'C';
  74.     var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum 
  75.         FROM pg_class c, pg_attribute a,pg_type t 
  76.         WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
  77. AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
  78.  
  79.     // used when schema defined
  80.     var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum 
  81. FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n 
  82. WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
  83.  and c.relnamespace=n.oid and n.nspname='%s' 
  84.     and a.attname not like '....%%' AND a.attnum > 0 
  85.     AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
  86.     
  87.     // get primary key etc -- from Freek Dijkstra
  88.     var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key 
  89.     FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";
  90.     
  91.     var $hasAffectedRows = true;
  92.     var $hasLimit = false;    // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
  93.     // below suggested by Freek Dijkstra 
  94.     var $true = 'TRUE';        // string that represents TRUE for a database
  95.     var $false = 'FALSE';        // string that represents FALSE for a database
  96.     var $fmtDate = "'Y-m-d'";    // used by DBDate() as the default date format used by the database
  97.     var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
  98.     var $hasMoveFirst = true;
  99.     var $hasGenID = true;
  100.     var $_genIDSQL = "SELECT NEXTVAL('%s')";
  101.     var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
  102.     var $_dropSeqSQL = "DROP SEQUENCE %s";
  103.     var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
  104.     var $random = 'random()';        /// random function
  105.     var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4
  106.                             // http://bugs.php.net/bug.php?id=25404
  107.                             
  108.     var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
  109.     var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance.
  110.     
  111.     // The last (fmtTimeStamp is not entirely correct: 
  112.     // PostgreSQL also has support for time zones, 
  113.     // and writes these time in this format: "2001-03-01 18:59:26+02". 
  114.     // There is no code for the "+02" time zone information, so I just left that out. 
  115.     // I'm not familiar enough with both ADODB as well as Postgres 
  116.     // to know what the concequences are. The other values are correct (wheren't in 0.94)
  117.     // -- Freek Dijkstra 
  118.  
  119.     function ADODB_postgres64() 
  120.     {
  121.     // changes the metaColumnsSQL, adds columns: attnum[6]
  122.     }
  123.     
  124.     function ServerInfo()
  125.     {
  126.         if (isset($this->version)) return $this->version;
  127.         
  128.         $arr['description'] = $this->GetOne("select version()");
  129.         $arr['version'] = ADOConnection::_findvers($arr['description']);
  130.         $this->version = $arr;
  131.         return $arr;
  132.     }
  133.  
  134.     function IfNull( $field, $ifNull ) 
  135.     {
  136.         return " coalesce($field, $ifNull) "; 
  137.     }
  138.  
  139.     // get the last id - never tested
  140.     function pg_insert_id($tablename,$fieldname)
  141.     {
  142.         $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");
  143.         if ($result) {
  144.             $arr = @pg_fetch_row($result,0);
  145.             pg_freeresult($result);
  146.             if (isset($arr[0])) return $arr[0];
  147.         }
  148.         return false;
  149.     }
  150.     
  151. /* Warning from http://www.php.net/manual/function.pg-getlastoid.php:
  152. Using a OID as a unique identifier is not generally wise. 
  153. Unless you are very careful, you might end up with a tuple having 
  154. a different OID if a database must be reloaded. */
  155.     function _insertid($table,$column)
  156.     {
  157.         if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
  158.         $oid = pg_getlastoid($this->_resultid);
  159.         // to really return the id, we need the table and column-name, else we can only return the oid != id
  160.         return empty($table) || empty($column) ? $oid : $this->GetOne("SELECT $column FROM $table WHERE oid=".(int)$oid);
  161.     }
  162.  
  163. // I get this error with PHP before 4.0.6 - jlim
  164. // Warning: This compilation does not support pg_cmdtuples() in d:/inetpub/wwwroot/php/adodb/adodb-postgres.inc.php on line 44
  165.    function _affectedrows()
  166.    {
  167.            if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
  168.            return pg_cmdtuples($this->_resultid);
  169.    }
  170.    
  171.     
  172.         // returns true/false
  173.     function BeginTrans()
  174.     {
  175.         if ($this->transOff) return true;
  176.         $this->transCnt += 1;
  177.         return @pg_Exec($this->_connectionID, "begin");
  178.     }
  179.     
  180.     function RowLock($tables,$where,$flds='1 as ignore') 
  181.     {
  182.         if (!$this->transCnt) $this->BeginTrans();
  183.         return $this->GetOne("select $flds from $tables where $where for update");
  184.     }
  185.  
  186.     // returns true/false. 
  187.     function CommitTrans($ok=true) 
  188.     { 
  189.         if ($this->transOff) return true;
  190.         if (!$ok) return $this->RollbackTrans();
  191.         
  192.         $this->transCnt -= 1;
  193.         return @pg_Exec($this->_connectionID, "commit");
  194.     }
  195.     
  196.     // returns true/false
  197.     function RollbackTrans()
  198.     {
  199.         if ($this->transOff) return true;
  200.         $this->transCnt -= 1;
  201.         return @pg_Exec($this->_connectionID, "rollback");
  202.     }
  203.     
  204.     function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
  205.     {
  206.         $info = $this->ServerInfo();
  207.         if ($info['version'] >= 7.3) {
  208.             $this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
  209.               and schemaname  not in ( 'pg_catalog','information_schema')
  210.     union 
  211.         select viewname,'V' from pg_views where viewname not like 'pg\_%'  and schemaname  not in ( 'pg_catalog','information_schema') ";
  212.         }
  213.         if ($mask) {
  214.             $save = $this->metaTablesSQL;
  215.             $mask = $this->qstr(strtolower($mask));
  216.             if ($info['version']>=7.3)
  217.                 $this->metaTablesSQL = "
  218. select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema')  
  219.  union 
  220. select viewname,'V' from pg_views where viewname like $mask and schemaname  not in ( 'pg_catalog','information_schema')  ";
  221.             else
  222.                 $this->metaTablesSQL = "
  223. select tablename,'T' from pg_tables where tablename like $mask 
  224.  union 
  225. select viewname,'V' from pg_views where viewname like $mask";
  226.         }
  227.         $ret =& ADOConnection::MetaTables($ttype,$showSchema);
  228.         
  229.         if ($mask) {
  230.             $this->metaTablesSQL = $save;
  231.         }
  232.         return $ret;
  233.     }
  234.     
  235.     /*
  236.     // if magic quotes disabled, use pg_escape_string()
  237.     function qstr($s,$magic_quotes=false)
  238.     {
  239.         if (!$magic_quotes) {
  240.             if (ADODB_PHPVER >= 0x4200) {
  241.                 return  "'".pg_escape_string($s)."'";
  242.             }
  243.             if ($this->replaceQuote[0] == '\\'){
  244.                 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  245.             }
  246.             return  "'".str_replace("'",$this->replaceQuote,$s)."'"; 
  247.         }
  248.         
  249.         // undo magic quotes for "
  250.         $s = str_replace('\\"','"',$s);
  251.         return "'$s'";
  252.     }
  253.     */
  254.     
  255.     
  256.     // Format date column in sql string given an input format that understands Y M D
  257.     function SQLDate($fmt, $col=false)
  258.     {    
  259.         if (!$col) $col = $this->sysTimeStamp;
  260.         $s = 'TO_CHAR('.$col.",'";
  261.         
  262.         $len = strlen($fmt);
  263.         for ($i=0; $i < $len; $i++) {
  264.             $ch = $fmt[$i];
  265.             switch($ch) {
  266.             case 'Y':
  267.             case 'y':
  268.                 $s .= 'YYYY';
  269.                 break;
  270.             case 'Q':
  271.             case 'q':
  272.                 $s .= 'Q';
  273.                 break;
  274.                 
  275.             case 'M':
  276.                 $s .= 'Mon';
  277.                 break;
  278.                 
  279.             case 'm':
  280.                 $s .= 'MM';
  281.                 break;
  282.             case 'D':
  283.             case 'd':
  284.                 $s .= 'DD';
  285.                 break;
  286.             
  287.             case 'H':
  288.                 $s.= 'HH24';
  289.                 break;
  290.                 
  291.             case 'h':
  292.                 $s .= 'HH';
  293.                 break;
  294.                 
  295.             case 'i':
  296.                 $s .= 'MI';
  297.                 break;
  298.             
  299.             case 's':
  300.                 $s .= 'SS';
  301.                 break;
  302.             
  303.             case 'a':
  304.             case 'A':
  305.                 $s .= 'AM';
  306.                 break;
  307.                 
  308.             case 'w':
  309.                 $s .= 'D';
  310.                 break;
  311.             
  312.             case 'l':
  313.                 $s .= 'DAY';
  314.                 break;
  315.                 
  316.             default:
  317.             // handle escape characters...
  318.                 if ($ch == '\\') {
  319.                     $i++;
  320.                     $ch = substr($fmt,$i,1);
  321.                 }
  322.                 if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
  323.                 else $s .= '"'.$ch.'"';
  324.                 
  325.             }
  326.         }
  327.         return $s. "')";
  328.     }
  329.     
  330.     
  331.     
  332.     /* 
  333.     * Load a Large Object from a file 
  334.     * - the procedure stores the object id in the table and imports the object using 
  335.     * postgres proprietary blob handling routines 
  336.     *
  337.     * contributed by Mattia Rossi mattia@technologist.com
  338.     * modified for safe mode by juraj chlebec
  339.     */ 
  340.     function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') 
  341.     { 
  342.         pg_exec ($this->_connectionID, "begin"); 
  343.         
  344.         $fd = fopen($path,'r');
  345.         $contents = fread($fd,filesize($path));
  346.         fclose($fd);
  347.         
  348.         $oid = pg_lo_create($this->_connectionID);
  349.         $handle = pg_lo_open($this->_connectionID, $oid, 'w');
  350.         pg_lo_write($handle, $contents);
  351.         pg_lo_close($handle);
  352.         
  353.         // $oid = pg_lo_import ($path); 
  354.         pg_exec($this->_connectionID, "commit"); 
  355.         $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype); 
  356.         $rez = !empty($rs); 
  357.         return $rez; 
  358.     } 
  359.     
  360.     /*
  361.         Hueristic - not guaranteed to work.
  362.     */
  363.     function GuessOID($oid)
  364.     {
  365.         if (strlen($oid)>16) return false;
  366.         return is_numeric($oid);
  367.     }
  368.     
  369.     /* 
  370.     * If an OID is detected, then we use pg_lo_* to open the oid file and read the
  371.     * real blob from the db using the oid supplied as a parameter. If you are storing
  372.     * blobs using bytea, we autodetect and process it so this function is not needed.
  373.     *
  374.     * contributed by Mattia Rossi mattia@technologist.com
  375.     *
  376.     * see http://www.postgresql.org/idocs/index.php?largeobjects.html
  377.     *
  378.     * Since adodb 4.54, this returns the blob, instead of sending it to stdout. Also
  379.     * added maxsize parameter, which defaults to $db->maxblobsize if not defined.
  380.     */ 
  381.     function BlobDecode($blob,$maxsize=false,$hastrans=true) 
  382.     {
  383.         if (!$this->GuessOID($blob)) return $blob;
  384.         
  385.         if ($hastrans) @pg_exec($this->_connectionID,"begin"); 
  386.         $fd = @pg_lo_open($this->_connectionID,$blob,"r");
  387.         if ($fd === false) {
  388.             if ($hastrans) @pg_exec($this->_connectionID,"commit");
  389.             return $blob;
  390.         }
  391.         if (!$maxsize) $maxsize = $this->maxblobsize;
  392.         $realblob = @pg_loread($fd,$maxsize); 
  393.         @pg_loclose($fd); 
  394.         if ($hastrans) @pg_exec($this->_connectionID,"commit"); 
  395.         return $realblob;
  396.     } 
  397.     
  398.     /* 
  399.         See http://www.postgresql.org/idocs/index.php?datatype-binary.html
  400.          
  401.         NOTE: SQL string literals (input strings) must be preceded with two backslashes 
  402.         due to the fact that they must pass through two parsers in the PostgreSQL 
  403.         backend.
  404.     */
  405.     function BlobEncode($blob)
  406.     {
  407.         if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);
  408.         
  409.         /*92=backslash, 0=null, 39=single-quote*/
  410.         $badch = array(chr(92),chr(0),chr(39)); # \  null  '
  411.         $fixch = array('\\\\134','\\\\000','\\\\047');
  412.         return adodb_str_replace($badch,$fixch,$blob);
  413.         
  414.         // note that there is a pg_escape_bytea function only for php 4.2.0 or later
  415.     }
  416.     
  417.     // assumes bytea for blob, and varchar for clob
  418.     function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  419.     {
  420.     
  421.         if ($blobtype == 'CLOB') {
  422.             return $this->Execute("UPDATE $table SET $column=" . $this->qstr($val) . " WHERE $where");
  423.         }
  424.         // do not use bind params which uses qstr(), as blobencode() already quotes data
  425.         return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");
  426.     }
  427.     
  428.     function OffsetDate($dayFraction,$date=false)
  429.     {        
  430.         if (!$date) $date = $this->sysDate;
  431.         return "($date+interval'$dayFraction days')";
  432.     }
  433.     
  434.  
  435.     // for schema support, pass in the $table param "$schema.$tabname".
  436.     // converts field names to lowercase, $upper is ignored
  437.     function &MetaColumns($table,$normalize=true) 
  438.     {
  439.     global $ADODB_FETCH_MODE;
  440.     
  441.         $schema = false;
  442.         $this->_findschema($table,$schema);
  443.         
  444.         if ($normalize) $table = strtolower($table);
  445.  
  446.         $save = $ADODB_FETCH_MODE;
  447.         $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  448.         if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  449.         
  450.         if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
  451.         else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
  452.         if (isset($savem)) $this->SetFetchMode($savem);
  453.         $ADODB_FETCH_MODE = $save;
  454.         
  455.         if ($rs === false) {
  456.             $false = false;
  457.             return $false;
  458.         }
  459.         if (!empty($this->metaKeySQL)) {
  460.             // If we want the primary keys, we have to issue a separate query
  461.             // Of course, a modified version of the metaColumnsSQL query using a 
  462.             // LEFT JOIN would have been much more elegant, but postgres does 
  463.             // not support OUTER JOINS. So here is the clumsy way.
  464.             
  465.             $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  466.             
  467.             $rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
  468.             // fetch all result in once for performance.
  469.             $keys =& $rskey->GetArray();
  470.             if (isset($savem)) $this->SetFetchMode($savem);
  471.             $ADODB_FETCH_MODE = $save;
  472.             
  473.             $rskey->Close();
  474.             unset($rskey);
  475.         }
  476.  
  477.         $rsdefa = array();
  478.         if (!empty($this->metaDefaultsSQL)) {
  479.             $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  480.             $sql = sprintf($this->metaDefaultsSQL, ($table));
  481.             $rsdef = $this->Execute($sql);
  482.             if (isset($savem)) $this->SetFetchMode($savem);
  483.             $ADODB_FETCH_MODE = $save;
  484.             
  485.             if ($rsdef) {
  486.                 while (!$rsdef->EOF) {
  487.                     $num = $rsdef->fields['num'];
  488.                     $s = $rsdef->fields['def'];
  489.                     if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
  490.                         $s = substr($s, 1);
  491.                         $s = substr($s, 0, strlen($s) - 1);
  492.                     }
  493.  
  494.                     $rsdefa[$num] = $s;
  495.                     $rsdef->MoveNext();
  496.                 }
  497.             } else {
  498.                 ADOConnection::outp( "==> SQL => " . $sql);
  499.             }
  500.             unset($rsdef);
  501.         }
  502.     
  503.         $retarr = array();
  504.         while (!$rs->EOF) {     
  505.             $fld = new ADOFieldObject();
  506.             $fld->name = $rs->fields[0];
  507.             $fld->type = $rs->fields[1];
  508.             $fld->max_length = $rs->fields[2];
  509.             if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
  510.             if ($fld->max_length <= 0) $fld->max_length = -1;
  511.             if ($fld->type == 'numeric') {
  512.                 $fld->scale = $fld->max_length & 0xFFFF;
  513.                 $fld->max_length >>= 16;
  514.             }
  515.             // dannym
  516.             // 5 hasdefault; 6 num-of-column
  517.             $fld->has_default = ($rs->fields[5] == 't');
  518.             if ($fld->has_default) {
  519.                 $fld->default_value = $rsdefa[$rs->fields[6]];
  520.             }
  521.  
  522.             //Freek
  523.             if ($rs->fields[4] == $this->true) {
  524.                 $fld->not_null = true;
  525.             }
  526.             
  527.             // Freek
  528.             if (is_array($keys)) {
  529.                 foreach($keys as $key) {
  530.                     if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) 
  531.                         $fld->primary_key = true;
  532.                     if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) 
  533.                         $fld->unique = true; // What name is more compatible?
  534.                 }
  535.             }
  536.             
  537.             if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;    
  538.             else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld;
  539.             
  540.             $rs->MoveNext();
  541.         }
  542.         $rs->Close();
  543.         return empty($retarr) ? false : $retarr;    
  544.         
  545.     }
  546.  
  547.       function &MetaIndexes ($table, $primary = FALSE)
  548.       {
  549.          global $ADODB_FETCH_MODE;
  550.                 
  551.                 $schema = false;
  552.                 $this->_findschema($table,$schema);
  553.  
  554.                 if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
  555.                     $sql = '
  556. SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" 
  557. FROM pg_catalog.pg_class c 
  558. JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid 
  559. JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
  560.     ,pg_namespace n 
  561. WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\' AND i.indisprimary=false';
  562.                 } else {
  563.                     $sql = '
  564. SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
  565. FROM pg_catalog.pg_class c
  566. JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
  567. JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
  568. WHERE c2.relname=\'%s\' or c2.relname=lower(\'%s\')';
  569.                 }
  570.                             
  571.                 if ($primary == FALSE) {
  572.                     $sql .= ' AND i.indisprimary=false;';
  573.                 }
  574.                 
  575.                 $save = $ADODB_FETCH_MODE;
  576.                 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  577.                 if ($this->fetchMode !== FALSE) {
  578.                         $savem = $this->SetFetchMode(FALSE);
  579.                 }
  580.                 
  581.                 $rs = $this->Execute(sprintf($sql,$table,$table,$schema));
  582.                 if (isset($savem)) {
  583.                         $this->SetFetchMode($savem);
  584.                 }
  585.                 $ADODB_FETCH_MODE = $save;
  586.  
  587.                 if (!is_object($rs)) {
  588.                     $false = false;
  589.                     return $false;
  590.                 }
  591.                 
  592.                 $col_names = $this->MetaColumnNames($table,true);
  593.                 $indexes = array();
  594.                 while ($row = $rs->FetchRow()) {
  595.                         $columns = array();
  596.                         foreach (explode(' ', $row[2]) as $col) {
  597.                                 $columns[] = $col_names[$col - 1];
  598.                         }
  599.                         
  600.                         $indexes[$row[0]] = array(
  601.                                 'unique' => ($row[1] == 't'),
  602.                                 'columns' => $columns
  603.                         );
  604.                 }
  605.                 return $indexes;
  606.         }
  607.  
  608.     // returns true or false
  609.     //
  610.     // examples:
  611.     //     $db->Connect("host=host1 user=user1 password=secret port=4341");
  612.     //     $db->Connect('host1','user1','secret');
  613.     function _connect($str,$user='',$pwd='',$db='',$ctype=0)
  614.     {
  615.         
  616.         if (!function_exists('pg_pconnect')) return null;
  617.         
  618.         $this->_errorMsg = false;
  619.         
  620.         if ($user || $pwd || $db) {
  621.             $user = adodb_addslashes($user);
  622.             $pwd = adodb_addslashes($pwd);
  623.             if (strlen($db) == 0) $db = 'template1';
  624.             $db = adodb_addslashes($db);
  625.                if ($str)  {
  626.                  $host = split(":", $str);
  627.                 if ($host[0]) $str = "host=".adodb_addslashes($host[0]);
  628.                 else $str = 'host=localhost';
  629.                 if (isset($host[1])) $str .= " port=$host[1]";
  630.             }
  631.                    if ($user) $str .= " user=".$user;
  632.                    if ($pwd)  $str .= " password=".$pwd;
  633.                 if ($db)   $str .= " dbname=".$db;
  634.         }
  635.  
  636.         //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";
  637.         
  638.         if ($ctype === 1) { // persistent
  639.             $this->_connectionID = pg_pconnect($str);
  640.         } else {
  641.             if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str
  642.             static $ncnt;
  643.             
  644.                 if (empty($ncnt)) $ncnt = 1;
  645.                 else $ncnt += 1;
  646.                 
  647.                 $str .= str_repeat(' ',$ncnt);
  648.             }
  649.             $this->_connectionID = pg_connect($str);
  650.         }
  651.         if ($this->_connectionID === false) return false;
  652.         $this->Execute("set datestyle='ISO'");
  653.         return true;
  654.     }
  655.     
  656.     function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  657.     {
  658.          return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1);
  659.     }
  660.      
  661.     // returns true or false
  662.     //
  663.     // examples:
  664.     //     $db->PConnect("host=host1 user=user1 password=secret port=4341");
  665.     //     $db->PConnect('host1','user1','secret');
  666.     function _pconnect($str,$user='',$pwd='',$db='')
  667.     {
  668.         return $this->_connect($str,$user,$pwd,$db,1);
  669.     }
  670.     
  671.  
  672.     // returns queryID or false
  673.     function _query($sql,$inputarr)
  674.     {
  675.         
  676.         if ($inputarr) {
  677.         /*
  678.             It appears that PREPARE/EXECUTE is slower for many queries.
  679.             
  680.             For query executed 1000 times:
  681.             "select id,firstname,lastname from adoxyz 
  682.                 where firstname not like ? and lastname not like ? and id = ?"
  683.                 
  684.             with plan = 1.51861286163 secs
  685.             no plan =   1.26903700829 secs
  686.  
  687.             
  688.  
  689.         */
  690.             $plan = 'P'.md5($sql);
  691.                 
  692.             $execp = '';
  693.             foreach($inputarr as $v) {
  694.                 if ($execp) $execp .= ',';
  695.                 if (is_string($v)) {
  696.                     if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v);
  697.                 } else {
  698.                     $execp .= $v;
  699.                 }
  700.             }
  701.             
  702.             if ($execp) $exsql = "EXECUTE $plan ($execp)";
  703.             else $exsql = "EXECUTE $plan";
  704.             
  705.             $rez = @pg_exec($this->_connectionID,$exsql);
  706.             if (!$rez) {
  707.             # Perhaps plan does not exist? Prepare/compile plan.
  708.                 $params = '';
  709.                 foreach($inputarr as $v) {
  710.                     if ($params) $params .= ',';
  711.                     if (is_string($v)) {
  712.                         $params .= 'VARCHAR';
  713.                     } else if (is_integer($v)) {
  714.                         $params .= 'INTEGER';
  715.                     } else {
  716.                         $params .= "REAL";
  717.                     }
  718.                 }
  719.                 $sqlarr = explode('?',$sql);
  720.                 //print_r($sqlarr);
  721.                 $sql = '';
  722.                 $i = 1;
  723.                 foreach($sqlarr as $v) {
  724.                     $sql .= $v.' $'.$i;
  725.                     $i++;
  726.                 }
  727.                 $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2);        
  728.                 //adodb_pr($s);
  729.                 pg_exec($this->_connectionID,$s);
  730.                 echo $this->ErrorMsg();
  731.             }
  732.             
  733.             $rez = pg_exec($this->_connectionID,$exsql);
  734.         } else {
  735.             $this->_errorMsg = false;
  736.             //adodb_backtrace();
  737.             $rez = pg_exec($this->_connectionID,$sql);
  738.         }
  739.         // check if no data returned, then no need to create real recordset
  740.         if ($rez && pg_numfields($rez) <= 0) {
  741.             if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {
  742.                 pg_freeresult($this->_resultid);
  743.             }
  744.             $this->_resultid = $rez;
  745.             return true;
  746.         }
  747.         
  748.         return $rez;
  749.     }
  750.     
  751.  
  752.     /*    Returns: the last error message from previous database operation    */    
  753.     function ErrorMsg() 
  754.     {
  755.         if ($this->_errorMsg !== false) return $this->_errorMsg;
  756.         if (ADODB_PHPVER >= 0x4300) {
  757.             if (!empty($this->_resultid)) {
  758.                 $this->_errorMsg = @pg_result_error($this->_resultid);
  759.                 if ($this->_errorMsg) return $this->_errorMsg;
  760.             }
  761.             
  762.             if (!empty($this->_connectionID)) {
  763.                 $this->_errorMsg = @pg_last_error($this->_connectionID);
  764.             } else $this->_errorMsg = @pg_last_error();
  765.         } else {
  766.             if (empty($this->_connectionID)) $this->_errorMsg = @pg_errormessage();
  767.             else $this->_errorMsg = @pg_errormessage($this->_connectionID);
  768.         }
  769.         return $this->_errorMsg;
  770.     }
  771.     
  772.     function ErrorNo()
  773.     {
  774.         $e = $this->ErrorMsg();
  775.         if (strlen($e)) {
  776.             return ADOConnection::MetaError($e);
  777.          }
  778.          return 0;
  779.     }
  780.  
  781.     // returns true or false
  782.     function _close()
  783.     {
  784.         if ($this->transCnt) $this->RollbackTrans();
  785.         if ($this->_resultid) {
  786.             @pg_freeresult($this->_resultid);
  787.             $this->_resultid = false;
  788.         }
  789.         @pg_close($this->_connectionID);
  790.         $this->_connectionID = false;
  791.         return true;
  792.     }
  793.     
  794.     
  795.     /*
  796.     * Maximum size of C field
  797.     */
  798.     function CharMax()
  799.     {
  800.         return 1000000000;  // should be 1 Gb?
  801.     }
  802.     
  803.     /*
  804.     * Maximum size of X field
  805.     */
  806.     function TextMax()
  807.     {
  808.         return 1000000000; // should be 1 Gb?
  809.     }
  810.     
  811.         
  812. }
  813.     
  814. /*--------------------------------------------------------------------------------------
  815.      Class Name: Recordset
  816. --------------------------------------------------------------------------------------*/
  817.  
  818. class ADORecordSet_postgres64 extends ADORecordSet{
  819.     var $_blobArr;
  820.     var $databaseType = "postgres64";
  821.     var $canSeek = true;
  822.     function ADORecordSet_postgres64($queryID,$mode=false) 
  823.     {
  824.         if ($mode === false) { 
  825.             global $ADODB_FETCH_MODE;
  826.             $mode = $ADODB_FETCH_MODE;
  827.         }
  828.         switch ($mode)
  829.         {
  830.         case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
  831.         case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
  832.         
  833.         case ADODB_FETCH_DEFAULT:
  834.         case ADODB_FETCH_BOTH:
  835.         default: $this->fetchMode = PGSQL_BOTH; break;
  836.         }
  837.         $this->adodbFetchMode = $mode;
  838.         $this->ADORecordSet($queryID);
  839.     }
  840.     
  841.     function &GetRowAssoc($upper=true)
  842.     {
  843.         if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;
  844.         $row =& ADORecordSet::GetRowAssoc($upper);
  845.         return $row;
  846.     }
  847.  
  848.     function _initrs()
  849.     {
  850.     global $ADODB_COUNTRECS;
  851.         $qid = $this->_queryID;
  852.         $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):-1;
  853.         $this->_numOfFields = @pg_numfields($qid);
  854.         
  855.         // cache types for blob decode check
  856.         // apparently pg_fieldtype actually performs an sql query on the database to get the type.
  857.         if (empty($this->connection->noBlobs))
  858.         for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) {  
  859.             if (pg_fieldtype($qid,$i) == 'bytea') {
  860.                 $this->_blobArr[$i] = pg_fieldname($qid,$i);
  861.             }
  862.         }
  863.     }
  864.  
  865.         /* Use associative array to get fields array */
  866.     function Fields($colname)
  867.     {
  868.         if ($this->fetchMode != PGSQL_NUM) return @$this->fields[$colname];
  869.         
  870.         if (!$this->bind) {
  871.             $this->bind = array();
  872.             for ($i=0; $i < $this->_numOfFields; $i++) {
  873.                 $o = $this->FetchField($i);
  874.                 $this->bind[strtoupper($o->name)] = $i;
  875.             }
  876.         }
  877.          return $this->fields[$this->bind[strtoupper($colname)]];
  878.     }
  879.  
  880.     function &FetchField($off = 0) 
  881.     {
  882.         // offsets begin at 0
  883.         
  884.         $o= new ADOFieldObject();
  885.         $o->name = @pg_fieldname($this->_queryID,$off);
  886.         $o->type = @pg_fieldtype($this->_queryID,$off);
  887.         $o->max_length = @pg_fieldsize($this->_queryID,$off);
  888.         return $o;    
  889.     }
  890.  
  891.     function _seek($row)
  892.     {
  893.         return @pg_fetch_row($this->_queryID,$row);
  894.     }
  895.     
  896.     function _decode($blob)
  897.     {
  898.         eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
  899.         return $realblob;    
  900.     }
  901.     
  902.     function _fixblobs()
  903.     {
  904.         if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) {
  905.             foreach($this->_blobArr as $k => $v) {
  906.                 $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]);
  907.             }
  908.         }
  909.         if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) {
  910.             foreach($this->_blobArr as $k => $v) {
  911.                 $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]);
  912.             }
  913.         }
  914.     }
  915.     
  916.     // 10% speedup to move MoveNext to child class
  917.     function MoveNext() 
  918.     {
  919.         if (!$this->EOF) {
  920.             $this->_currentRow++;
  921.             if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
  922.                 $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
  923.                 if (is_array($this->fields) && $this->fields) {
  924.                     if (isset($this->_blobArr)) $this->_fixblobs();
  925.                     return true;
  926.                 }
  927.             }
  928.             $this->fields = false;
  929.             $this->EOF = true;
  930.         }
  931.         return false;
  932.     }        
  933.     
  934.     function _fetch()
  935.     {
  936.                 
  937.         if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)
  938.             return false;
  939.  
  940.         $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
  941.         
  942.         if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
  943.             
  944.         return (is_array($this->fields));
  945.     }
  946.  
  947.     function _close() 
  948.     { 
  949.         return @pg_freeresult($this->_queryID);
  950.     }
  951.  
  952.     function MetaType($t,$len=-1,$fieldobj=false)
  953.     {
  954.         if (is_object($t)) {
  955.             $fieldobj = $t;
  956.             $t = $fieldobj->type;
  957.             $len = $fieldobj->max_length;
  958.         }
  959.         switch (strtoupper($t)) {
  960.                 case 'MONEY': // stupid, postgres expects money to be a string
  961.                 case 'INTERVAL':
  962.                 case 'CHAR':
  963.                 case 'CHARACTER':
  964.                 case 'VARCHAR':
  965.                 case 'NAME':
  966.                    case 'BPCHAR':
  967.                 case '_VARCHAR':
  968.                 case 'INET':
  969.                     if ($len <= $this->blobSize) return 'C';
  970.                 
  971.                 case 'TEXT':
  972.                     return 'X';
  973.         
  974.                 case 'IMAGE': // user defined type
  975.                 case 'BLOB': // user defined type
  976.                 case 'BIT':    // This is a bit string, not a single bit, so don't return 'L'
  977.                 case 'VARBIT':
  978.                 case 'BYTEA':
  979.                     return 'B';
  980.                 
  981.                 case 'BOOL':
  982.                 case 'BOOLEAN':
  983.                     return 'L';
  984.                 
  985.                 case 'DATE':
  986.                     return 'D';
  987.                 
  988.                 case 'TIME':
  989.                 case 'DATETIME':
  990.                 case 'TIMESTAMP':
  991.                 case 'TIMESTAMPTZ':
  992.                     return 'T';
  993.                 
  994.                 case 'SMALLINT': 
  995.                 case 'BIGINT': 
  996.                 case 'INTEGER': 
  997.                 case 'INT8': 
  998.                 case 'INT4':
  999.                 case 'INT2':
  1000.                     if (isset($fieldobj) &&
  1001.                 empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';
  1002.                 
  1003.                 case 'OID':
  1004.                 case 'SERIAL':
  1005.                     return 'R';
  1006.                 
  1007.                  default:
  1008.                      return 'N';
  1009.             }
  1010.     }
  1011.  
  1012. }
  1013. ?>